<template>
  <div class="main">
    <a-form :form="form" autocomplete="off">
      <div class="main-box">
        <div class="main-item" v-for="item in formItem" :key="item.key">
          <div class="top-title" v-if="!item.hasHidden">
            <div>{{ item.label }}<span v-if="item.require" class="tigs">（必填）</span></div>
            <div class="addItem" v-if="item.propsType == 'selects'" @click="handleAddItem">添加行政区</div>
          </div>
          <a-form-item>
            <!-- 选择器 -->
            <a-select
              v-if="item.propsType == 'select' && !item.hasHidden"
              v-decorator="[`${item.key}`, { initialValue: dataForm[item.key] }]"
              :placeholder="item.placeholder || '请选择'"
              :disabled="isLook"
            >
              <a-select-option v-for="it in item.propsOptions" :key="it.key" :value="it.value">
                {{ it.name }}
              </a-select-option>
            </a-select>
            <a-select
              v-else-if="item.propsType == 'multipleSelect' && !item.hasHidden"
              v-decorator="[`${item.key}`, { initialValue: dataForm[item.key] }]"
              mode="multiple"
              :placeholder="item.placeholder || '请选择'"
              :disabled="isLook"
              optionFilterProp="label"
            >
              <a-select-option v-for="it in item.propsOptions" :key="it.id" :value="it.id" :label="it.areaName">
                {{ it.areaName }}
              </a-select-option>
            </a-select>
            <!-- 多个选择器 -->
            <template v-else-if="item.propsType == 'selects' && !item.hasHidden">
              <!-- <a-select
                v-for="(i, ix) in selectList"
                :key="i"
                v-decorator="[`${item.key}`, { initialValue: dataForm[item.key][ix] }]"
                :placeholder="item.placeholder || '请选择'"
                :disabled="isLook"
              >
                <a-select-option v-for="it in item.propsOptions" :key="it.key" :value="it.value">
                  {{ it.name }}
                </a-select-option>
              </a-select> -->
              <div class="mySelect" v-for="(ite, ix) in selectList" :key="ix">
                <!-- <a-tree-select
                  showSearch
                  :replaceFields="replaceFields"
                  treeNodeFilterProp="title"
                  style="width: 95%"
                  v-model="selectList[ix]"
                  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                  placeholder="请选择"
                  :tree-data="item.propsOptions"
                /> -->
                <a-cascader
                  v-model="ite.value"
                  :fieldNames="replaceFields"
                  :options="item.propsOptions"
                  change-on-select
                  :allowClear="false"
                  placeholder="请选择"
                />
                <a-icon style="color: #fff" type="delete" @click="ondeleteItem(ix)" />
              </div>
            </template>

            <!-- 上传图片 -->
            <div v-else-if="item.propsType == 'upload' && !item.hasHidden">
              <div v-if="!isLook">
                <a-upload
                  accept="image/png,image/jpg,image/jpeg,image/bmp"
                  :before-upload="beforeUpload"
                  :action="action"
                  :headers="headers"
                  :data="{ type: item.type || 12 }"
                  list-type="picture-card"
                  :file-list="fileList"
                  @preview="handlePreview"
                  @change="handleChange"
                >
                  <div v-if="fileList.length < item.limit">
                    <img src="@/assets/home/photo.png" />
                  </div>
                </a-upload>
                <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
                  <img alt="example" style="width: 100%" :src="previewImage" />
                </a-modal>
                <div class="upload-text" v-if="!item.hasNoTigs">
                  <div>1、请上传.jpg、.png、.bmp等图片格式文件；</div>
                  <div>2、图片上传数量不超过5张；</div>
                </div>
              </div>
              <div v-else>
                <a-carousel v-if="fileList.length" arrows>
                  <!-- <div slot="prevArrow" class="custom-slick-arrow" style="left: 10px; z-index: 1">
                    <a-icon type="left-circle" />
                  </div>
                  <div slot="nextArrow" class="custom-slick-arrow" style="right: 10px">
                    <a-icon type="right-circle" />
                  </div>
                  <div class="my-banner" v-for="(item, index) in fileList" :key="index">
                    <img :src="item.url" />
                  </div> -->

                  <viewer :images="fileList">
                    <div class="image-box">
                      <div v-for="(src, index) in fileList" class="imgBox">
                        <img class="myImage" :src="src.url" />
                      </div>
                    </div>
                  </viewer>
                </a-carousel>
                <div class="noBanner" v-else>暂无相关照片</div>
              </div>
            </div>
            <!-- 富文本 -->
            <div v-else-if="item.propsType == 'editor' && !item.hasHidden">
              <!-- <Editor :isLook="isLook" :value.sync="dataForm[item.key]" @change="changeEditor" /> -->
              <editor :disabled="isLook" v-model="yourContent"></editor>
            </div>

            <!-- 文本域 -->
            <a-textarea
              v-else-if="item.propsType == 'textarea' && !item.hasHidden"
              v-decorator="[`${item.key}`, { initialValue: dataForm[item.key] }]"
              :placeholder="isLook ? '暂无内容' : '请输入'"
              :autoSize="{ minRows: 4, maxRows: 8 }"
              :disabled="isLook"
              :maxLength="1024"
              style="font-size: 16px"
            />
            <!-- 验证码 -->
            <div
              style="display: flex; align-items: center"
              v-else-if="item.propsType == 'phoneCode' && !item.hasHidden"
            >
              <a-input
                v-decorator="[`${item.key}`, { initialValue: dataForm[item.key] }]"
                placeholder="请输入验证码"
                :maxLength="6"
                style="width: 58%"
                ref="code"
              >
              </a-input>
              <a-button class="my-btn" @click="getCode" :disabled="codeStatus" style="width: 40%; margin-left: 2%">{{
                phoneCode
              }}</a-button>
            </div>

            <!-- 密码框 -->
            <a-input-password
              v-else-if="item.propsType == 'password' && !item.hasHidden"
              v-decorator="[`${item.key}`, { initialValue: dataForm[item.key] }]"
              placeholder="请输入密码"
              allow-clear
              ref="password"
            >
              <svg-icon icon="password" :size="14" slot="prefix"> </svg-icon>
            </a-input-password>
            <!-- 文本 -->
            <a-input
              v-else-if="item.propsType == 'input' && !item.hasHidden"
              v-decorator="[`${item.key}`, { initialValue: dataForm[item.key] }]"
              :placeholder="item.placeholder || '请输入'"
              :suffix="item.hasSuffix && item.suffix"
              :disabled="isLook"
              :maxLength="item.maxLength || null"
              @change="item.onChange && item.onChange()"
            />
          </a-form-item>
        </div>
      </div>
      <a-divider v-if="!isLook" />
      <a-divider v-if="isLook && showFooter" />

      <a-form-item v-if="!isLook">
        <div class="my-btn">
          <a-button class="cancel" @click="cancel">取消</a-button>
          <a-button type="primary" @click="handleSubmit"> {{ confimText }} </a-button>
        </div>
      </a-form-item>
      <a-form-item v-if="isLook && showFooter">
        <div class="my-btn">
          <a-button class="cancel" @click="cancel">取消</a-button>
          <a-button type="primary" @click="handleEdit"> {{ confimText }} </a-button>
        </div>
      </a-form-item>
    </a-form>
  </div>
</template>

<script>
import { getCache, setCache, removeCache } from '@/utils/session';

import { isPhone, isPassWord, isCode } from '@/utils/validate';
import { getPhoneCode, readFile } from '@/api/user';
// import Editor from '@/views/components/editor';

import Editor from '@/views/components/newEditor';

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}
export default {
  components: { Editor },
  props: {
    dataForm: {
      type: Object,
      default: () => {
        return {};
      }
    },
    formItem: {
      type: Array,
      default: () => {
        return [];
      }
    },
    isLook: {
      type: Boolean,
      default: false
    },
    confimText: {
      type: String,
      default: '提交审核'
    },
    showFooter: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    dataForm(nl, ol) {
      if (nl.id) {
        console.log(nl);
        this.setForm();
      }
    }
  },

  mounted() {
    this.setForm();
  },
  data() {
    return {
      dataFormNew: {},
      fileList: [],
      previewVisible: false,
      previewImage: '',
      ruleForm: {},
      codeStatus: false,
      phoneCode: '获取验证码',
      headers: {
        'API-User-Token': getCache('TOKEN')
      },
      selectList: [
        {
          value: []
        }
      ],
      replaceFields: {
        children: 'children',
        label: 'areaName',
        value: 'id'
      },
      cascaderValue: [],
      editorValue: '',
      action:
        process.env.NODE_ENV === 'development' ? '/api/hydrobim/upload/uploadFile' : '/hydrobim/upload/uploadFile',
      currentIndex: '',
      yourContent: ''
    };
  },
  beforeCreate() {
    this.form = this.$form.createForm(this, { name: 'validate_other' });
  },
  methods: {
    beforeUpload(file) {
      //判断格式
      if (!this.isImage(file)) {
        this.$message.warning('只能选择.jpg .png .bmp文件');
        return false;
      }
      //判断大小
      if (file.size / 1024 / 1024 > 10) {
        this.$message.warning('上传图片大小不能超过10M');
        return false;
      }
    },
    isImage(file) {
      return /\.(bmp|jpg|jpeg|png)$/.test(file.name);
    },
    handleSubmit() {
      this.form.validateFields((err, values) => {
        if (!err) {
          let selectNewList = this.selectList.filter(item => item.value.length);
          if (selectNewList.length) {
            let provinceArr = [];
            let cityArr = [];
            selectNewList.map(item => {
              provinceArr.push(item.value[0]);
              if (item.value[1]) {
                cityArr.push(item.value[1]);
              } else {
                cityArr.push('999');
              }
            });

            values.provinceId = provinceArr.join(',');
            values.cityId = cityArr.join(',');
          }
          if (this.fileList.length) {
            let arr = [];
            this.fileList.map(item => {
              if (item.realUrl) {
                arr.push(item.realUrl);
              } else {
                arr.push(item.response.data.fileIds[0]);
              }
            });
            let uploadObj = this.formItem.filter(item => item.propsType == 'upload')[0];
            values[uploadObj.key] = arr.join(',');
          }
          let multipleObj = this.formItem.filter(item => item.propsType == 'multipleSelect');
          if (multipleObj.length && values[multipleObj[0].key]) {
            if (values[multipleObj[0].key].length > 3) {
              this.$message.info('所属流域最多选择3个');
              return;
            }
            values[multipleObj[0].key] = values[multipleObj[0].key].join(',');
          }
          // 富文本
          if (this.yourContent) {
            let uploadObj = this.formItem.filter(item => item.propsType == 'editor')[0];
            values[uploadObj.key] = this.yourContent;
          }

          this.$emit('handleSubmit', values);
        }
      });
    },
    handleEdit() {
      this.$emit('handleEdit');
    },
    setForm() {
      this.formItem.map(item => {
        if (item.propsType == 'upload') {
          if (item.key == 'portrait') {
            this.fileList = [];
            if (this.dataForm[item.key]) {
              this.dataForm[item.key].split(',').map((it, index) => {
                readFile(it).then(res => {
                  this.fileList.push({
                    uid: index,
                    name: 'touxiang.png',
                    status: 'done',
                    url: res.data,
                    src: res.data,
                    realUrl: it
                  });
                });
              });
            }
          } else {
            this.fileList = [];
            if (this.dataForm[item.key]) {
              this.dataForm[item.key].split(',').map((it, index) => {
                this.fileList.push({
                  uid: index,
                  name: 'touxiang.png',
                  status: 'done',
                  url: it,
                  src: it,
                  realUrl: it
                });
              });
            }
          }
        } else if (item.propsType == 'selects') {
          this.selectList = [
            {
              value: []
            }
          ];
          if (this.dataForm.provinceId) {
            let provinceArr = this.dataForm.provinceId.split(',');
            let cityArr = this.dataForm.cityId.split(',');
            let arr = [];
            provinceArr.map((i, index) => {
              if (cityArr[index] == '999') {
                let obj = {
                  value: [i]
                };
                arr.push(obj);
              } else {
                let obj = {
                  value: [i, cityArr[index]]
                };
                arr.push(obj);
              }
            });
            console.log('11123', arr);
            this.selectList = arr;
          }
          // this.selectList = [];
          // if (this.dataForm[item.key]) {
          //   this.dataForm[item.key].split(',').map((it, index) => {
          //     this.selectList.push(it);
          //   });
          // } else {
          //   this.selectList = [''];
          // }
        } else if (item.propsType == 'multipleSelect') {
          if (this.dataForm[item.key] && this.dataForm[item.key] != '') {
            this.dataForm[item.key] = this.dataForm[item.key].split(',');
          } else {
            this.dataForm[item.key] = [];
          }
        } else if (item.propsType == 'editor') {
          this.yourContent = this.dataForm[item.key];
        }
      });
    },
    cancel() {
      this.$emit('cancel');
    },
    resetFields() {
      this.form.resetFields();
    },
    handleCancel() {
      this.previewVisible = false;
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      this.previewImage = file.url || file.preview;
      this.previewVisible = true;
    },
    handleChange({ fileList }) {
      this.fileList = fileList.filter(item => item.status);
    },
    // 添加
    handleAddItem() {
      if (this.selectList.length > 2) {
        this.$message.info('所属行政区最多选择3个');
        return;
      }
      this.selectList.push({ value: [] });
    },
    // 删除
    ondeleteItem(index) {
      if (this.selectList.length == 1) {
        this.$message.info('最少选择一个行政区');
        return;
      }
      this.selectList.splice(index, 1);
    },
    //获取验证码
    getCode() {
      this.form.validateFields((err, values) => {
        if (isPhone(values.userAccount)) {
          this.codeStatus = true;
          getPhoneCode(values.userAccount)
            .then(res => {
              let time = 60;
              var getPhoneIntval = setInterval(() => {
                if (time > 0) {
                  time--;
                  this.phoneCode = `重新获取(${time}s)`;
                } else {
                  clearInterval(getPhoneIntval);
                  getPhoneIntval = null;
                  this.phoneCode = '获取验证码';
                  this.codeStatus = false;
                }
              }, 1000);
              this.$refs.code.focus();
            })
            .catch(() => {
              this.codeStatus = false;
            });
        } else {
          this.$message.error('请正确输入手机号');
        }
      });
    },
    changeEditor(value) {
      this.yourContent = value;
    },

    handleWheel(event) {
      // 滚轮向上滚动，放大图片
      if (event.deltaY < 0) {
        this.scale *= 1.1; // 可以根据需要调整缩放系数
      }
      // 滚轮向下滚动，缩小图片
      else {
        this.scale /= 1.1; // 可以根据需要调整缩放系数
      }

      // 限制最小和最大缩放比例，以防图片过大或过小
      if (this.scale < 0.1) {
        this.scale = 0.1;
      }
      if (this.scale > 3) {
        this.scale = 3;
      }
    }
  }
};
</script>

<style scoped lang="scss">
.main {
  padding: 0 24px;

  .mySelect {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 4px;
  }

  .main-item {
    color: #fff;
    font-size: 16px;
    margin-bottom: 8px;

    .top-title {
      display: flex;
      justify-content: space-between;

      .addItem {
        color: #1666f0;
      }
    }

    .tigs {
      font-size: 14px;
      color: rgba(255, 255, 255, 0.5);
    }

    .ant-form-item {
      margin-bottom: 0;
    }

    .ant-input {
      background: rgba(22, 102, 240, 0.2);
      border: 1px solid #1666f0;
      color: #fff;
    }

    .my-btn {
      color: #ccc;
      background: #021c2e;
      border: 1px solid #1666f0;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }

  .main-item ::v-deep .ant-input-suffix {
    color: #fff;
  }
  .main-item ::v-deep .ant-input-password-icon {
    color: #fff !important;
  }

  .main-item ::v-deep .ant-input {
    background: rgba(22, 102, 240, 0.2);
    border: 1px solid #1666f0;
    color: #fff;
  }

  .main-item ::v-deep .ant-select-selection {
    background: rgba(22, 102, 240, 0.2);
    border: 1px solid #1666f0;
    color: #fff;
  }

  .main-item ::v-deep .ant-select-arrow {
    color: #fff !important;
  }

  .main-item ::v-deep .ant-select-selection__choice {
    color: #fff;
    background: none;
  }

  .main-item ::v-deep .ant-cascader-picker {
    color: #fff;
    background: rgba(22, 102, 240, 0.2);
  }
  .main-item ::v-deep .ant-cascader-picker-arrow {
    color: #fff !important;
  }

  .main-item ::v-deep .ant-cascader-picker-clear {
    background: none;
  }

  .main-item ::v-deep i {
    // color: #fff;
  }

  .main-item ::v-deep .ant-upload {
    background: rgba(22, 102, 240, 0.2);
    border: 1px solid #1666f0;
  }

  .main-box {
    max-height: calc(100vh - 266px);
    overflow: hidden;
    overflow-y: auto;

    .upload-text {
      color: rgba(255, 255, 255, 0.5);
      font-size: 14px;
      line-height: 18px;
    }
  }

  .main-box::-webkit-scrollbar {
    display: none;
    /*隐藏滚动条*/
  }

  .my-btn {
    display: flex;
    justify-content: flex-end;

    .cancel {
      margin-right: 20px;
      color: #fff;
      background: rgba(22, 102, 240, 0.2);
      border-color: rgba(22, 102, 240, 0.2);
    }
  }

  .my-banner {
    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }

  .noBanner {
    color: #fff;
  }

  .imgBox {
    position: relative;
  }

  .image-box {
    display: flex;
    flex-wrap: wrap;
  }

  .myImage {
    width: 300px;
    height: 300px;
    margin: 10px;
    cursor: url('~@/assets/home/add1.png') 16 16, auto;
  }
}
</style>
<style scoped>
/* For demo */
.ant-carousel >>> .slick-slide {
  text-align: center;
  background-color: #021c2e;
  overflow: hidden;
  overflow-y: auto;
}

.ant-carousel >>> .custom-slick-arrow {
  width: 25px;
  height: 25px;
  font-size: 25px;
  color: #fff;
  background-color: rgba(31, 45, 61, 0.11);
  opacity: 0.3;
}

.ant-carousel >>> .custom-slick-arrow:before {
  display: none;
}

.ant-carousel >>> .custom-slick-arrow:hover {
  opacity: 0.5;
}

.ant-carousel >>> .slick-slide h3 {
  color: #fff;
}

.overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
}

.preview-container {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.preview-container img {
  max-height: 80vh;
}
</style>
